#!/bin/bash

# JDK和Maven安装校验脚本
# 功能：验证JDK 21和Maven 3.9.x的安装是否成功
# 版本：1.0
# 作者：安装校验脚本生成器

# 设置脚本严格模式
set -euo pipefail

# 全局变量定义
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_DIR="${SCRIPT_DIR}/logs"
TEMP_DIR="${SCRIPT_DIR}/temp"
REPORT_DIR="${SCRIPT_DIR}/reports"

# 校验配置
JDK_VERSION="21"
MAVEN_VERSION="3.9.6"
VERIFY_JDK=true
VERIFY_MAVEN=true
RUN_INTEGRATION_TEST=true
GENERATE_REPORT=true

# 校验结果统计
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0
WARNING_TESTS=0

# 校验状态
VERIFY_SUCCESS=0      # 完全成功
VERIFY_WARNING=1      # 成功但有警告
VERIFY_PARTIAL=2      # 部分成功
VERIFY_FAILED=3       # 完全失败
VERIFY_SKIPPED=4      # 跳过校验
FINAL_STATUS=$VERIFY_SUCCESS

# 日志级别
LOG_LEVEL_DEBUG=0
LOG_LEVEL_INFO=1
LOG_LEVEL_WARN=2
LOG_LEVEL_ERROR=3
LOG_LEVEL_FATAL=4
CURRENT_LOG_LEVEL=$LOG_LEVEL_INFO

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 错误码定义
ERROR_SUCCESS=0
ERROR_GENERAL=1
ERROR_JDK_NOT_FOUND=1001
ERROR_MAVEN_NOT_FOUND=1002
ERROR_JAVA_HOME_MISSING=1003
ERROR_MAVEN_HOME_MISSING=1004
ERROR_JAVA_VERSION_MISMATCH=1005
ERROR_MAVEN_VERSION_MISMATCH=1006
ERROR_JAVA_FUNCTIONALITY=1007
ERROR_MAVEN_FUNCTIONALITY=1008
ERROR_INTEGRATION_TEST=1009

# =============================================================================
# 工具函数
# =============================================================================

# 显示帮助信息
show_help() {
    cat << EOF
JDK和Maven安装校验脚本

用法: $0 [选项]

选项:
    -h, --help          显示此帮助信息
    -v, --version       显示脚本版本
    -j, --jdk-only      仅校验JDK安装
    -m, --maven-only    仅校验Maven安装
    -r, --no-report     不生成详细报告
    -i, --no-integration 跳过集成测试
    --debug             启用调试模式
    --quiet             静默模式，仅显示错误

示例:
    $0                  校验JDK和Maven安装
    $0 -j               仅校验JDK安装
    $0 -m               仅校验Maven安装
    $0 --debug          启用调试模式

EOF
}

# 显示版本信息
show_version() {
    echo "JDK和Maven安装校验脚本 v1.0"
    echo "目标JDK版本: ${JDK_VERSION}"
    echo "目标Maven版本: ${MAVEN_VERSION}"
}

# 日志记录函数
log_message() {
    local level="$1"
    local message="$2"
    local module="${3:-MAIN}"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    local pid=$$
    
    # 检查日志级别
    case $level in
        "DEBUG") [[ $CURRENT_LOG_LEVEL -gt $LOG_LEVEL_DEBUG ]] && return ;;
        "INFO")  [[ $CURRENT_LOG_LEVEL -gt $LOG_LEVEL_INFO ]] && return ;;
        "WARN")  [[ $CURRENT_LOG_LEVEL -gt $LOG_LEVEL_WARN ]] && return ;;
        "ERROR") [[ $CURRENT_LOG_LEVEL -gt $LOG_LEVEL_ERROR ]] && return ;;
        "FATAL") [[ $CURRENT_LOG_LEVEL -gt $LOG_LEVEL_FATAL ]] && return ;;
    esac
    
    # 格式化日志消息
    local log_entry="[${timestamp}] [${level}] [${module}] [${pid}] ${message}"
    
    # 写入日志文件
    if [[ -d "$LOG_DIR" ]]; then
        echo "$log_entry" >> "${LOG_DIR}/verify_$(date +%Y%m%d_%H%M%S).log"
    fi
    
    # 控制台输出
    if [[ "${SILENT_MODE:-false}" != true ]]; then
        case $level in
            "DEBUG") echo -e "${BLUE}${log_entry}${NC}" ;;
            "INFO")  echo -e "${GREEN}${log_entry}${NC}" ;;
            "WARN")  echo -e "${YELLOW}${log_entry}${NC}" ;;
            "ERROR") echo -e "${RED}${log_entry}${NC}" ;;
            "FATAL") echo -e "${RED}${log_entry}${NC}" ;;
            *)       echo "$log_entry" ;;
        esac
    fi
}

# 便捷日志函数
log_debug() { log_message "DEBUG" "$1" "${2:-MAIN}"; }
log_info() { log_message "INFO" "$1" "${2:-MAIN}"; }
log_warn() { log_message "WARN" "$1" "${2:-MAIN}"; }
log_error() { log_message "ERROR" "$1" "${2:-MAIN}"; }
log_fatal() { log_message "FATAL" "$1" "${2:-MAIN}"; }

# 显示状态信息
show_status() {
    local status="$1"
    local message="$2"
    
    case $status in
        "success")
            echo -e "${GREEN}✓ ${message}${NC}"
            ((PASSED_TESTS++))
            ;;
        "warning")
            echo -e "${YELLOW}⚠ ${message}${NC}"
            ((WARNING_TESTS++))
            if [[ $FINAL_STATUS -lt $VERIFY_WARNING ]]; then
                FINAL_STATUS=$VERIFY_WARNING
            fi
            ;;
        "error")
            echo -e "${RED}✗ ${message}${NC}"
            ((FAILED_TESTS++))
            if [[ $FINAL_STATUS -lt $VERIFY_FAILED ]]; then
                FINAL_STATUS=$VERIFY_FAILED
            fi
            ;;
        "info")
            echo -e "${BLUE}ℹ ${message}${NC}"
            ;;
        "skip")
            echo -e "${YELLOW}- ${message}${NC}"
            ;;
    esac
    ((TOTAL_TESTS++))
}

# 显示进度条
show_progress() {
    local current="$1"
    local total="$2"
    local message="$3"
    
    local percent=$((current * 100 / total))
    local bar_length=50
    local filled_length=$((percent * bar_length / 100))
    
    printf "\r[%3d%%] [" $percent
    printf "%*s" $filled_length | tr ' ' '='
    printf "%*s] %s" $((bar_length - filled_length)) "" "$message"
}

# 检查命令是否存在
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# 创建必要的目录
create_directories() {
    log_debug "创建必要的目录" "SYSTEM_INIT"
    
    local dirs=("$LOG_DIR" "$TEMP_DIR" "$REPORT_DIR")
    
    for dir in "${dirs[@]}"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir" || {
                log_error "无法创建目录: $dir" "SYSTEM_INIT"
                return $ERROR_PERMISSION_DENIED
            }
            log_debug "已创建目录: $dir" "SYSTEM_INIT"
        fi
    done
    
    return 0
}

# =============================================================================
# JDK校验函数
# =============================================================================

# 初始化JDK校验
verify_jdk_init() {
    if [[ "$VERIFY_JDK" != true ]]; then
        log_info "跳过JDK校验" "JDK_VERIFY"
        return 1
    fi
    
    log_info "开始JDK校验" "JDK_VERIFY"
    return 0
}

# 校验JAVA_HOME环境变量
verify_java_home() {
    log_info "检查JAVA_HOME环境变量" "JDK_VERIFY"
    
    if [[ -z "${JAVA_HOME:-}" ]]; then
        show_status "error" "JAVA_HOME环境变量未设置"
        log_error "JAVA_HOME环境变量未设置" "JDK_VERIFY"
        return $ERROR_JAVA_HOME_MISSING
    fi
    
    if [[ ! -d "$JAVA_HOME" ]]; then
        show_status "error" "JAVA_HOME目录不存在: $JAVA_HOME"
        log_error "JAVA_HOME目录不存在: $JAVA_HOME" "JDK_VERIFY"
        return $ERROR_JAVA_HOME_MISSING
    fi
    
    if [[ ! -f "$JAVA_HOME/bin/java" ]]; then
        show_status "error" "JAVA_HOME/bin/java文件不存在"
        log_error "JAVA_HOME/bin/java文件不存在" "JDK_VERIFY"
        return $ERROR_JAVA_HOME_MISSING
    fi
    
    show_status "success" "JAVA_HOME环境变量正确: $JAVA_HOME"
    log_info "JAVA_HOME环境变量正确: $JAVA_HOME" "JDK_VERIFY"
    return 0
}

# 校验Java命令可用性
verify_java_command() {
    log_info "检查Java命令可用性" "JDK_VERIFY"
    
    if ! command_exists java; then
        show_status "error" "java命令不可用"
        log_error "java命令不可用" "JDK_VERIFY"
        return $ERROR_JDK_NOT_FOUND
    fi
    
    if ! command_exists javac; then
        show_status "error" "javac命令不可用"
        log_error "javac命令不可用" "JDK_VERIFY"
        return $ERROR_JDK_NOT_FOUND
    fi
    
    show_status "success" "Java命令可用"
    log_info "Java命令可用" "JDK_VERIFY"
    return 0
}

# 校验Java版本
verify_java_version() {
    log_info "检查Java版本" "JDK_VERIFY"
    
    local java_version_output=$(java -version 2>&1)
    local java_version=$(echo "$java_version_output" | head -n 1 | cut -d'"' -f2)
    
    if [[ -z "$java_version" ]]; then
        show_status "error" "无法获取Java版本信息"
        log_error "无法获取Java版本信息" "JDK_VERIFY"
        return $ERROR_JAVA_VERSION_MISMATCH
    fi
    
    if [[ ! "$java_version" == *"$JDK_VERSION"* ]]; then
        show_status "warning" "Java版本不匹配: 期望${JDK_VERSION}, 实际${java_version}"
        log_warn "Java版本不匹配: 期望${JDK_VERSION}, 实际${java_version}" "JDK_VERIFY"
        return $ERROR_JAVA_VERSION_MISMATCH
    fi
    
    show_status "success" "Java版本正确: $java_version"
    log_info "Java版本正确: $java_version" "JDK_VERIFY"
    return 0
}

# 校验Java目录结构
verify_java_structure() {
    log_info "检查Java安装目录结构" "JDK_VERIFY"
    
    local required_dirs=("bin" "lib" "conf" "include" "jmods")
    local missing_dirs=()
    
    for dir in "${required_dirs[@]}"; do
        if [[ ! -d "$JAVA_HOME/$dir" ]]; then
            missing_dirs+=("$dir")
        fi
    done
    
    if [[ ${#missing_dirs[@]} -gt 0 ]]; then
        show_status "warning" "Java安装缺少目录: ${missing_dirs[*]}"
        log_warn "Java安装缺少目录: ${missing_dirs[*]}" "JDK_VERIFY"
        return 1
    fi
    
    show_status "success" "Java安装目录结构完整"
    log_info "Java安装目录结构完整" "JDK_VERIFY"
    return 0
}

# 测试Java基本功能
verify_java_functionality() {
    log_info "测试Java基本功能" "JDK_VERIFY"
    
    local test_dir="${TEMP_DIR}/java_test"
    mkdir -p "$test_dir"
    
    # 创建测试Java文件
    cat > "$test_dir/HelloWorld.java" << 'EOF'
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        System.out.println("Java功能测试成功");
    }
}
EOF
    
    # 编译测试
    if ! (cd "$test_dir" && javac HelloWorld.java); then
        show_status "error" "Java编译测试失败"
        log_error "Java编译测试失败" "JDK_VERIFY"
        rm -rf "$test_dir"
        return $ERROR_JAVA_FUNCTIONALITY
    fi
    
    # 运行测试
    if ! (cd "$test_dir" && java HelloWorld); then
        show_status "error" "Java运行测试失败"
        log_error "Java运行测试失败" "JDK_VERIFY"
        rm -rf "$test_dir"
        return $ERROR_JAVA_FUNCTIONALITY
    fi
    
    # 清理测试文件
    rm -rf "$test_dir"
    
    show_status "success" "Java基本功能测试通过"
    log_info "Java基本功能测试通过" "JDK_VERIFY"
    return 0
}

# 执行完整的JDK校验
verify_jdk() {
    if ! verify_jdk_init; then
        return 1
    fi
    
    log_info "执行JDK完整校验" "JDK_VERIFY"
    
    local jdk_tests=(
        "verify_java_home"
        "verify_java_command"
        "verify_java_version"
        "verify_java_structure"
        "verify_java_functionality"
    )
    
    local failed_tests=0
    
    for test in "${jdk_tests[@]}"; do
        if ! $test; then
            ((failed_tests++))
        fi
    done
    
    if [[ $failed_tests -eq 0 ]]; then
        log_info "JDK校验完全通过" "JDK_VERIFY"
        return 0
    else
        log_warn "JDK校验完成，有${failed_tests}项失败" "JDK_VERIFY"
        return 1
    fi
}

# =============================================================================
# Maven校验函数
# =============================================================================

# 初始化Maven校验
verify_maven_init() {
    if [[ "$VERIFY_MAVEN" != true ]]; then
        log_info "跳过Maven校验" "MAVEN_VERIFY"
        return 1
    fi
    
    log_info "开始Maven校验" "MAVEN_VERIFY"
    return 0
}

# 校验MAVEN_HOME环境变量
verify_maven_home() {
    log_info "检查MAVEN_HOME环境变量" "MAVEN_VERIFY"
    
    # 如果MAVEN_HOME未设置，尝试自动检测
    if [[ -z "${MAVEN_HOME:-}" ]]; then
        log_info "MAVEN_HOME未设置，尝试自动检测" "MAVEN_VERIFY"
        
        # 方法1：检查常见的Maven安装目录
        local possible_maven_dirs=(
            "$HOME/maven/apache-maven-3.9.11"
            "$HOME/maven/apache-maven-3.9.6"
            "$HOME/maven/apache-maven-3.9.4"
            "$HOME/maven/apache-maven-3.9.2"
            "$HOME/maven/apache-maven-3.9.0"
            "$HOME/maven/apache-maven-3.8.8"
            "$HOME/maven/apache-maven-3.8.6"
            "$HOME/maven/apache-maven-3.8.4"
            "$HOME/maven/apache-maven-3.8.3"
            "$HOME/maven/apache-maven-3.8.1"
            "$HOME/maven/apache-maven-3.8.0"
            "$HOME/maven/apache-maven-3.6.3"
            "$HOME/maven/apache-maven-3.6.2"
            "$HOME/maven/apache-maven-3.6.1"
            "$HOME/maven/apache-maven-3.6.0"
            "$HOME/maven/apache-maven-3.5.4"
            "$HOME/maven/apache-maven-3.5.3"
            "$HOME/maven/apache-maven-3.5.2"
            "$HOME/maven/apache-maven-3.5.0"
            "$HOME/maven/apache-maven-3.3.9"
            "$HOME/maven/apache-maven-3.3.8"
            "$HOME/maven/apache-maven-3.3.7"
            "$HOME/maven/apache-maven-3.3.6"
            "$HOME/maven/apache-maven-3.3.5"
            "$HOME/maven/apache-maven-3.3.4"
            "$HOME/maven/apache-maven-3.3.3"
            "$HOME/maven/apache-maven-3.3.2"
            "$HOME/maven/apache-maven-3.3.1"
            "$HOME/maven/apache-maven-3.3.0"
            "$HOME/maven/apache-maven-3.2.5"
            "$HOME/maven/apache-maven-3.2.3"
            "$HOME/maven/apache-maven-3.2.2"
            "$HOME/maven/apache-maven-3.2.1"
            "$HOME/maven/apache-maven-3.2.0"
            "$HOME/maven/apache-maven-3.1.1"
            "$HOME/maven/apache-maven-3.1.0"
            "$HOME/maven/apache-maven-3.0.5"
            "$HOME/maven/apache-maven-3.0.4"
            "$HOME/maven/apache-maven-3.0.3"
            "$HOME/maven/apache-maven-3.0.2"
            "$HOME/maven/apache-maven-3.0.1"
            "$HOME/maven/apache-maven-3.0.0"
            "$HOME/maven/maven"
            "/opt/maven/apache-maven-3.9.11"
            "/opt/maven/apache-maven-3.9.6"
            "/opt/maven/apache-maven-3.9.4"
            "/opt/maven/apache-maven-3.9.2"
            "/opt/maven/apache-maven-3.9.0"
            "/opt/maven/apache-maven-3.8.8"
            "/opt/maven/apache-maven-3.8.6"
            "/opt/maven/apache-maven-3.8.4"
            "/opt/maven/apache-maven-3.8.3"
            "/opt/maven/apache-maven-3.8.1"
            "/opt/maven/apache-maven-3.8.0"
            "/opt/maven/apache-maven-3.6.3"
            "/opt/maven/apache-maven-3.6.2"
            "/opt/maven/apache-maven-3.6.1"
            "/opt/maven/apache-maven-3.6.0"
            "/opt/maven/apache-maven-3.5.4"
            "/opt/maven/apache-maven-3.5.3"
            "/opt/maven/apache-maven-3.5.2"
            "/opt/maven/apache-maven-3.5.0"
            "/opt/maven/apache-maven-3.3.9"
            "/opt/maven/apache-maven-3.3.8"
            "/opt/maven/apache-maven-3.3.7"
            "/opt/maven/apache-maven-3.3.6"
            "/opt/maven/apache-maven-3.3.5"
            "/opt/maven/apache-maven-3.3.4"
            "/opt/maven/apache-maven-3.3.3"
            "/opt/maven/apache-maven-3.3.2"
            "/opt/maven/apache-maven-3.3.1"
            "/opt/maven/apache-maven-3.3.0"
            "/opt/maven/apache-maven-3.2.5"
            "/opt/maven/apache-maven-3.2.3"
            "/opt/maven/apache-maven-3.2.2"
            "/opt/maven/apache-maven-3.2.1"
            "/opt/maven/apache-maven-3.2.0"
            "/opt/maven/apache-maven-3.1.1"
            "/opt/maven/apache-maven-3.1.0"
            "/opt/maven/apache-maven-3.0.5"
            "/opt/maven/apache-maven-3.0.4"
            "/opt/maven/apache-maven-3.0.3"
            "/opt/maven/apache-maven-3.0.2"
            "/opt/maven/apache-maven-3.0.1"
            "/opt/maven/apache-maven-3.0.0"
            "/opt/maven/maven"
            "/usr/local/maven/apache-maven-3.9.11"
            "/usr/local/maven/apache-maven-3.9.6"
            "/usr/local/maven/apache-maven-3.9.4"
            "/usr/local/maven/apache-maven-3.9.2"
            "/usr/local/maven/apache-maven-3.9.0"
            "/usr/local/maven/apache-maven-3.8.8"
            "/usr/local/maven/apache-maven-3.8.6"
            "/usr/local/maven/apache-maven-3.8.4"
            "/usr/local/maven/apache-maven-3.8.3"
            "/usr/local/maven/apache-maven-3.8.1"
            "/usr/local/maven/apache-maven-3.8.0"
            "/usr/local/maven/apache-maven-3.6.3"
            "/usr/local/maven/apache-maven-3.6.2"
            "/usr/local/maven/apache-maven-3.6.1"
            "/usr/local/maven/apache-maven-3.6.0"
            "/usr/local/maven/apache-maven-3.5.4"
            "/usr/local/maven/apache-maven-3.5.3"
            "/usr/local/maven/apache-maven-3.5.2"
            "/usr/local/maven/apache-maven-3.5.0"
            "/usr/local/maven/apache-maven-3.3.9"
            "/usr/local/maven/apache-maven-3.3.8"
            "/usr/local/maven/apache-maven-3.3.7"
            "/usr/local/maven/apache-maven-3.3.6"
            "/usr/local/maven/apache-maven-3.3.5"
            "/usr/local/maven/apache-maven-3.3.4"
            "/usr/local/maven/apache-maven-3.3.3"
            "/usr/local/maven/apache-maven-3.3.2"
            "/usr/local/maven/apache-maven-3.3.1"
            "/usr/local/maven/apache-maven-3.3.0"
            "/usr/local/maven/apache-maven-3.2.5"
            "/usr/local/maven/apache-maven-3.2.3"
            "/usr/local/maven/apache-maven-3.2.2"
            "/usr/local/maven/apache-maven-3.2.1"
            "/usr/local/maven/apache-maven-3.2.0"
            "/usr/local/maven/apache-maven-3.1.1"
            "/usr/local/maven/apache-maven-3.1.0"
            "/usr/local/maven/apache-maven-3.0.5"
            "/usr/local/maven/apache-maven-3.0.4"
            "/usr/local/maven/apache-maven-3.0.3"
            "/usr/local/maven/apache-maven-3.0.2"
            "/usr/local/maven/apache-maven-3.0.1"
            "/usr/local/maven/apache-maven-3.0.0"
            "/usr/local/maven/maven"
        )
        
        for dir in "${possible_maven_dirs[@]}"; do
            if [[ -d "$dir" && -f "$dir/bin/mvn" ]]; then
                export MAVEN_HOME="$dir"
                log_info "自动检测到MAVEN_HOME: $MAVEN_HOME" "MAVEN_VERIFY"
                break
            fi
        done
    fi
    
    # 方法2：从配置文件中读取MAVEN_HOME
    if [[ -z "${MAVEN_HOME:-}" ]]; then
        log_info "尝试从配置文件中读取MAVEN_HOME" "MAVEN_VERIFY"
        
        # 检查shell配置文件
        local config_files=(
            "$HOME/.bashrc"
            "$HOME/.bash_profile"
            "$HOME/.profile"
            "$HOME/.zshrc"
        )
        
        for config_file in "${config_files[@]}"; do
            if [[ -f "$config_file" ]]; then
                local maven_home_from_config=$(grep "export MAVEN_HOME=" "$config_file" 2>/dev/null | tail -1 | cut -d'=' -f2 | tr -d '"')
                if [[ -n "$maven_home_from_config" && -d "$maven_home_from_config" && -f "$maven_home_from_config/bin/mvn" ]]; then
                    export MAVEN_HOME="$maven_home_from_config"
                    log_info "从配置文件中读取MAVEN_HOME: $MAVEN_HOME" "MAVEN_VERIFY"
                    break
                fi
            fi
        done
    fi
    
    # 方法3：使用which命令查找mvn
    if [[ -z "${MAVEN_HOME:-}" ]] && command_exists mvn; then
        log_info "使用which命令查找mvn" "MAVEN_VERIFY"
        
        local mvn_path=$(which mvn 2>/dev/null)
        if [[ -n "$mvn_path" ]]; then
            local detected_maven_home=$(dirname "$(dirname "$mvn_path")")
            if [[ -d "$detected_maven_home" && -f "$detected_maven_home/bin/mvn" ]]; then
                export MAVEN_HOME="$detected_maven_home"
                log_info "通过which命令检测到MAVEN_HOME: $MAVEN_HOME" "MAVEN_VERIFY"
            fi
        fi
    fi
    
    # 最后检查MAVEN_HOME是否设置成功
    if [[ -z "${MAVEN_HOME:-}" ]]; then
        show_status "error" "MAVEN_HOME环境变量未设置且无法自动检测"
        log_error "MAVEN_HOME环境变量未设置且无法自动检测" "MAVEN_VERIFY"
        return $ERROR_MAVEN_HOME_MISSING
    fi
    
    if [[ ! -d "$MAVEN_HOME" ]]; then
        show_status "error" "MAVEN_HOME目录不存在: $MAVEN_HOME"
        log_error "MAVEN_HOME目录不存在: $MAVEN_HOME" "MAVEN_VERIFY"
        return $ERROR_MAVEN_HOME_MISSING
    fi
    
    if [[ ! -f "$MAVEN_HOME/bin/mvn" ]]; then
        show_status "error" "MAVEN_HOME/bin/mvn文件不存在"
        log_error "MAVEN_HOME/bin/mvn文件不存在" "MAVEN_VERIFY"
        return $ERROR_MAVEN_HOME_MISSING
    fi
    
    show_status "success" "MAVEN_HOME环境变量正确: $MAVEN_HOME"
    log_info "MAVEN_HOME环境变量正确: $MAVEN_HOME" "MAVEN_VERIFY"
    return 0
}

# 校验Maven命令可用性
verify_maven_command() {
    log_info "检查Maven命令可用性" "MAVEN_VERIFY"
    
    # 如果MAVEN_HOME已设置且包含bin目录，临时添加到PATH
    if [[ -n "${MAVEN_HOME:-}" && -d "$MAVEN_HOME/bin" ]]; then
        # 检查PATH是否已包含Maven bin目录
        if [[ ":$PATH:" != *":$MAVEN_HOME/bin:"* ]]; then
            log_info "临时将Maven bin目录添加到PATH: $MAVEN_HOME/bin" "MAVEN_VERIFY"
            export PATH="$MAVEN_HOME/bin:$PATH"
        fi
    fi
    
    if ! command_exists mvn; then
        show_status "error" "mvn命令不可用"
        log_error "mvn命令不可用" "MAVEN_VERIFY"
        
        # 提供诊断信息
        if [[ -n "${MAVEN_HOME:-}" ]]; then
            log_error "MAVEN_HOME已设置: $MAVEN_HOME" "MAVEN_VERIFY"
            if [[ -f "$MAVEN_HOME/bin/mvn" ]]; then
                log_error "Maven可执行文件存在: $MAVEN_HOME/bin/mvn" "MAVEN_VERIFY"
                log_error "但PATH中不包含: $MAVEN_HOME/bin" "MAVEN_VERIFY"
                log_error "当前PATH: $PATH" "MAVEN_VERIFY"
            else
                log_error "Maven可执行文件不存在: $MAVEN_HOME/bin/mvn" "MAVEN_VERIFY"
            fi
        else
            log_error "MAVEN_HOME未设置" "MAVEN_VERIFY"
        fi
        
        return $ERROR_MAVEN_NOT_FOUND
    fi
    
    show_status "success" "Maven命令可用"
    log_info "Maven命令可用" "MAVEN_VERIFY"
    return 0
}

# 校验Maven版本
verify_maven_version() {
    log_info "检查Maven版本" "MAVEN_VERIFY"
    
    local maven_version_output=$(mvn -version 2>/dev/null)
    local maven_version=$(echo "$maven_version_output" | head -n 1 | awk '{print $3}')
    
    if [[ -z "$maven_version" ]]; then
        show_status "error" "无法获取Maven版本信息"
        log_error "无法获取Maven版本信息" "MAVEN_VERIFY"
        return $ERROR_MAVEN_VERSION_MISMATCH
    fi
    
    # 检查主版本号是否为3.9.x
    if [[ ! "$maven_version" == "3.9."* ]]; then
        show_status "warning" "Maven版本不匹配: 期望3.9.x, 实际${maven_version}"
        log_warn "Maven版本不匹配: 期望3.9.x, 实际${maven_version}" "MAVEN_VERIFY"
        return $ERROR_MAVEN_VERSION_MISMATCH
    fi
    
    show_status "success" "Maven版本正确: $maven_version"
    log_info "Maven版本正确: $maven_version" "MAVEN_VERIFY"
    return 0
}

# 校验Maven目录结构
verify_maven_structure() {
    log_info "检查Maven安装目录结构" "MAVEN_VERIFY"
    
    local required_dirs=("bin" "lib" "conf" "boot")
    local missing_dirs=()
    
    for dir in "${required_dirs[@]}"; do
        if [[ ! -d "$MAVEN_HOME/$dir" ]]; then
            missing_dirs+=("$dir")
        fi
    done
    
    if [[ ${#missing_dirs[@]} -gt 0 ]]; then
        show_status "warning" "Maven安装缺少目录: ${missing_dirs[*]}"
        log_warn "Maven安装缺少目录: ${missing_dirs[*]}" "MAVEN_VERIFY"
        return 1
    fi
    
    show_status "success" "Maven安装目录结构完整"
    log_info "Maven安装目录结构完整" "MAVEN_VERIFY"
    return 0
}

# 测试Maven基本功能
verify_maven_functionality() {
    log_info "测试Maven基本功能" "MAVEN_VERIFY"
    
    local test_dir="${TEMP_DIR}/maven_test"
    mkdir -p "$test_dir"
    
    # 创建测试pom.xml
    cat > "$test_dir/pom.xml" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>com.example</groupId>
    <artifactId>test-project</artifactId>
    <version>1.0.0</version>
    
    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
    </properties>
</project>
EOF
    
    # 测试Maven命令
    cd "$test_dir"
    if ! mvn help:effective-pom -q >/dev/null 2>&1; then
        show_status "error" "Maven基本功能测试失败"
        log_error "Maven基本功能测试失败" "MAVEN_VERIFY"
        cd "$SCRIPT_DIR"
        rm -rf "$test_dir"
        return $ERROR_MAVEN_FUNCTIONALITY
    fi
    cd "$SCRIPT_DIR"
    
    # 清理测试文件
    rm -rf "$test_dir"
    
    show_status "success" "Maven基本功能测试通过"
    log_info "Maven基本功能测试通过" "MAVEN_VERIFY"
    return 0
}

# 执行完整的Maven校验
verify_maven() {
    if ! verify_maven_init; then
        return 1
    fi
    
    log_info "执行Maven完整校验" "MAVEN_VERIFY"
    
    local maven_tests=(
        "verify_maven_home"
        "verify_maven_command"
        "verify_maven_version"
        "verify_maven_structure"
        "verify_maven_functionality"
    )
    
    local failed_tests=0
    
    for test in "${maven_tests[@]}"; do
        if ! $test; then
            ((failed_tests++))
        fi
    done
    
    if [[ $failed_tests -eq 0 ]]; then
        log_info "Maven校验完全通过" "MAVEN_VERIFY"
        return 0
    else
        log_warn "Maven校验完成，有${failed_tests}项失败" "MAVEN_VERIFY"
        return 1
    fi
}

# =============================================================================
# 环境变量校验函数
# =============================================================================

# 校验PATH环境变量
verify_path_environment() {
    log_info "检查PATH环境变量" "ENV_VERIFY"
    
    local path_contains_java=false
    local path_contains_maven=false
    
    # 检查PATH是否包含Java路径
    if [[ -n "${JAVA_HOME:-}" ]] && echo "$PATH" | grep -q "$JAVA_HOME/bin"; then
        path_contains_java=true
        show_status "success" "PATH包含Java路径: $JAVA_HOME/bin"
    else
        show_status "warning" "PATH不包含Java路径"
        log_warn "PATH不包含Java路径" "ENV_VERIFY"
    fi
    
    # 检查PATH是否包含Maven路径
    if [[ -n "${MAVEN_HOME:-}" ]] && echo "$PATH" | grep -q "$MAVEN_HOME/bin"; then
        path_contains_maven=true
        show_status "success" "PATH包含Maven路径: $MAVEN_HOME/bin"
    else
        show_status "warning" "PATH不包含Maven路径"
        log_warn "PATH不包含Maven路径" "ENV_VERIFY"
    fi
    
    if [[ "$path_contains_java" == true && "$path_contains_maven" == true ]]; then
        log_info "PATH环境变量配置正确" "ENV_VERIFY"
        return 0
    else
        log_warn "PATH环境变量配置不完整" "ENV_VERIFY"
        return 1
    fi
}

# 校验环境变量持久化配置
verify_environment_persistence() {
    log_info "检查环境变量持久化配置" "ENV_VERIFY"
    
    local shell_type=$(basename "$SHELL")
    local config_file=""
    local has_java_config=false
    local has_maven_config=false
    
    # 确定配置文件
    case $shell_type in
        bash)
            if [[ -f "$HOME/.bashrc" ]]; then
                config_file="$HOME/.bashrc"
            elif [[ -f "$HOME/.bash_profile" ]]; then
                config_file="$HOME/.bash_profile"
            else
                config_file="$HOME/.bashrc"
            fi
            ;;
        zsh)
            config_file="$HOME/.zshrc"
            ;;
        *)
            config_file="$HOME/.profile"
            ;;
    esac
    
    log_info "检查配置文件: $config_file" "ENV_VERIFY"
    
    if [[ -f "$config_file" ]]; then
        # 检查Java配置
        if grep -q "JAVA_HOME" "$config_file" 2>/dev/null; then
            has_java_config=true
            show_status "success" "配置文件包含JAVA_HOME设置"
        else
            show_status "warning" "配置文件不包含JAVA_HOME设置"
            log_warn "配置文件不包含JAVA_HOME设置" "ENV_VERIFY"
        fi
        
        # 检查Maven配置
        if grep -q "MAVEN_HOME" "$config_file" 2>/dev/null; then
            has_maven_config=true
            show_status "success" "配置文件包含MAVEN_HOME设置"
        else
            show_status "warning" "配置文件不包含MAVEN_HOME设置"
            log_warn "配置文件不包含MAVEN_HOME设置" "ENV_VERIFY"
        fi
    else
        show_status "warning" "配置文件不存在: $config_file"
        log_warn "配置文件不存在: $config_file" "ENV_VERIFY"
    fi
    
    if [[ "$has_java_config" == true && "$has_maven_config" == true ]]; then
        log_info "环境变量持久化配置正确" "ENV_VERIFY"
        return 0
    else
        log_warn "环境变量持久化配置不完整" "ENV_VERIFY"
        return 1
    fi
}

# 执行完整的环境变量校验
verify_environment() {
    log_info "执行环境变量校验" "ENV_VERIFY"
    
    local env_tests=(
        "verify_path_environment"
        "verify_environment_persistence"
    )
    
    local failed_tests=0
    
    for test in "${env_tests[@]}"; do
        if ! $test; then
            ((failed_tests++))
        fi
    done
    
    if [[ $failed_tests -eq 0 ]]; then
        log_info "环境变量校验完全通过" "ENV_VERIFY"
        return 0
    else
        log_warn "环境变量校验完成，有${failed_tests}项失败" "ENV_VERIFY"
        return 1
    fi
}

# =============================================================================
# 集成测试函数
# =============================================================================

# 执行JDK和Maven集成测试
verify_integration() {
    if [[ "$RUN_INTEGRATION_TEST" != true ]]; then
        log_info "跳过集成测试" "INTEGRATION_TEST"
        return 0
    fi
    
    log_info "执行JDK和Maven集成测试" "INTEGRATION_TEST"
    
    local test_dir="${TEMP_DIR}/integration_test"
    mkdir -p "$test_dir"
    
    # 创建完整的Maven项目
    cat > "$test_dir/pom.xml" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    
    <groupId>com.example</groupId>
    <artifactId>integration-test</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
    
    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.11.0</version>
                <configuration>
                    <source>21</source>
                    <target>21</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
EOF
    
    # 创建Java源码目录和文件
    mkdir -p "$test_dir/src/main/java/com/example"
    cat > "$test_dir/src/main/java/com/example/App.java" << 'EOF'
package com.example;

public class App {
    public static void main(String[] args) {
        System.out.println("集成测试成功!");
        System.out.println("JDK和Maven工作正常");
    }
}
EOF
    
    # 执行Maven编译
    cd "$test_dir"
    if ! mvn compile -q >/dev/null 2>&1; then
        show_status "error" "Maven编译测试失败"
        log_error "Maven编译测试失败" "INTEGRATION_TEST"
        cd "$SCRIPT_DIR"
        rm -rf "$test_dir"
        return $ERROR_INTEGRATION_TEST
    fi
    
    # 执行Maven打包
    if ! mvn package -q >/dev/null 2>&1; then
        show_status "error" "Maven打包测试失败"
        log_error "Maven打包测试失败" "INTEGRATION_TEST"
        cd "$SCRIPT_DIR"
        rm -rf "$test_dir"
        return $ERROR_INTEGRATION_TEST
    fi
    
    # 运行生成的JAR文件
    if ! java -cp target/integration-test-1.0.0.jar com.example.App; then
        show_status "error" "JAR文件运行测试失败"
        log_error "JAR文件运行测试失败" "INTEGRATION_TEST"
        cd "$SCRIPT_DIR"
        rm -rf "$test_dir"
        return $ERROR_INTEGRATION_TEST
    fi
    
    cd "$SCRIPT_DIR"
    rm -rf "$test_dir"
    
    show_status "success" "JDK和Maven集成测试通过"
    log_info "JDK和Maven集成测试通过" "INTEGRATION_TEST"
    return 0
}

# =============================================================================
# 报告生成函数
# =============================================================================

# 生成校验报告
generate_verification_report() {
    if [[ "$GENERATE_REPORT" != true ]]; then
        log_info "跳过报告生成" "REPORT"
        return 0
    fi
    
    log_info "生成校验报告" "REPORT"
    
    local report_file="${REPORT_DIR}/verification_report_$(date +%Y%m%d_%H%M%S).txt"
    
    cat > "$report_file" << EOF
JDK和Maven安装校验报告
=======================

校验时间: $(date '+%Y-%m-%d %H:%M:%S')
校验状态: $(get_status_text $FINAL_STATUS)
操作系统: $(uname -s) $(uname -r)
Shell: $SHELL

JDK ${JDK_VERSION} 校验结果
--------------
$(get_component_result "JDK")

Maven ${MAVEN_VERSION} 校验结果
------------------
$(get_component_result "Maven")

环境变量校验结果
--------------
$(get_component_result "环境变量")

集成测试结果
------------
$(get_component_result "集成测试")

安装摘要
--------
总校验项目: $TOTAL_TESTS
通过项目: $PASSED_TESTS
失败项目: $FAILED_TESTS
警告项目: $WARNING_TESTS

系统信息
--------
Java版本: $(java -version 2>&1 | head -n 1)
JAVA_HOME: ${JAVA_HOME:-未设置}
Maven版本: $(mvn -version 2>/dev/null | head -n 1 || echo "未安装")
MAVEN_HOME: ${MAVEN_HOME:-未设置}

建议和备注
--------
$(get_recommendations)

EOF
    
    log_info "校验报告已生成: $report_file" "REPORT"
    show_status "info" "详细报告已保存到: $report_file"
    
    return 0
}

# 获取状态文本
get_status_text() {
    local status="$1"
    
    case $status in
        $VERIFY_SUCCESS) echo "完全成功" ;;
        $VERIFY_WARNING) echo "成功但有警告" ;;
        $VERIFY_PARTIAL) echo "部分成功" ;;
        $VERIFY_FAILED) echo "校验失败" ;;
        $VERIFY_SKIPPED) echo "跳过校验" ;;
        *) echo "未知状态" ;;
    esac
}

# 获取组件校验结果
get_component_result() {
    local component="$1"
    
    case $component in
        "JDK")
            if [[ "$VERIFY_JDK" == true ]]; then
                if [[ $FAILED_TESTS -eq 0 ]]; then
                    echo "校验状态: ✓ 通过"
                else
                    echo "校验状态: ✗ 失败"
                fi
            else
                echo "校验状态: - 跳过"
            fi
            ;;
        "Maven")
            if [[ "$VERIFY_MAVEN" == true ]]; then
                if [[ $FAILED_TESTS -eq 0 ]]; then
                    echo "校验状态: ✓ 通过"
                else
                    echo "校验状态: ✗ 失败"
                fi
            else
                echo "校验状态: - 跳过"
            fi
            ;;
        "环境变量")
            echo "校验状态: ✓ 已完成"
            ;;
        "集成测试")
            if [[ "$RUN_INTEGRATION_TEST" == true ]]; then
                echo "校验状态: ✓ 通过"
            else
                echo "校验状态: - 跳过"
            fi
            ;;
        *)
            echo "校验状态: 未知"
            ;;
    esac
}

# 获取修复建议
get_recommendations() {
    local recommendations=""
    
    if [[ $FAILED_TESTS -gt 0 ]]; then
        recommendations+="检测到安装问题，建议如下：\n"
        
        if [[ $FAILED_TESTS -gt 0 ]]; then
            recommendations+="1. 重新运行安装脚本修复失败的组件\n"
            recommendations+="2. 检查环境变量配置是否正确\n"
            recommendations+="3. 确认安装目录权限设置正确\n"
        fi
    else
        recommendations+="安装完成，可以正常使用JDK和Maven进行开发。\n"
        recommendations+="建议：\n"
        recommendations+="1. 运行 'source ~/.bashrc' 使环境变量生效\n"
        recommendations+="2. 使用 'java -version' 和 'mvn -version' 验证安装\n"
    fi
    
    echo -e "$recommendations"
}

# 显示校验摘要
display_verification_summary() {
    echo
    echo "========================================"
    echo "           校验结果摘要"
    echo "========================================"
    echo
    echo "总校验项目: $TOTAL_TESTS"
    echo -e "通过项目: ${GREEN}$PASSED_TESTS${NC}"
    echo -e "失败项目: ${RED}$FAILED_TESTS${NC}"
    echo -e "警告项目: ${YELLOW}$WARNING_TESTS${NC}"
    echo
    echo -e "校验状态: $(get_status_color $FINAL_STATUS)$(get_status_text $FINAL_STATUS)${NC}"
    echo
    
    if [[ $FAILED_TESTS -gt 0 ]]; then
        echo -e "${RED}校验失败，请检查上述错误信息并重新安装${NC}"
        echo
    elif [[ $WARNING_TESTS -gt 0 ]]; then
        echo -e "${YELLOW}校验通过，但存在警告项${NC}"
        echo
    else
        echo -e "${GREEN}所有校验项目通过！${NC}"
        echo
    fi
}

# 获取状态颜色
get_status_color() {
    local status="$1"
    
    case $status in
        $VERIFY_SUCCESS) echo -e "${GREEN}" ;;
        $VERIFY_WARNING) echo -e "${YELLOW}" ;;
        $VERIFY_PARTIAL) echo -e "${YELLOW}" ;;
        $VERIFY_FAILED) echo -e "${RED}" ;;
        $VERIFY_SKIPPED) echo -e "${YELLOW}" ;;
        *) echo "" ;;
    esac
}

# =============================================================================
# 主函数
# =============================================================================

# 解析命令行参数
parse_arguments() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            -v|--version)
                show_version
                exit 0
                ;;
            -j|--jdk-only)
                VERIFY_JDK=true
                VERIFY_MAVEN=false
                shift
                ;;
            -m|--maven-only)
                VERIFY_JDK=false
                VERIFY_MAVEN=true
                shift
                ;;
            -r|--no-report)
                GENERATE_REPORT=false
                shift
                ;;
            -i|--no-integration)
                RUN_INTEGRATION_TEST=false
                shift
                ;;
            --debug)
                CURRENT_LOG_LEVEL=$LOG_LEVEL_DEBUG
                shift
                ;;
            --quiet)
                SILENT_MODE=true
                shift
                ;;
            *)
                log_error "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done
}

# 主校验流程
main() {
    log_info "开始JDK和Maven安装校验" "MAIN"
    
    # 解析命令行参数
    parse_arguments "$@"
    
    # 创建必要目录
    create_directories || {
        log_error "无法创建必要目录" "MAIN"
        exit $ERROR_GENERAL
    }
    
    echo "========================================"
    echo "      JDK和Maven安装校验脚本"
    echo "========================================"
    echo
    
    # 执行JDK校验
    if [[ "$VERIFY_JDK" == true ]]; then
        echo "开始JDK校验..."
        verify_jdk
        echo
    fi
    
    # 执行Maven校验
    if [[ "$VERIFY_MAVEN" == true ]]; then
        echo "开始Maven校验..."
        verify_maven
        echo
    fi
    
    # 执行环境变量校验
    echo "开始环境变量校验..."
    verify_environment
    echo
    
    # 执行集成测试
    if [[ "$VERIFY_JDK" == true && "$VERIFY_MAVEN" == true ]]; then
        echo "开始集成测试..."
        verify_integration
        echo
    fi
    
    # 生成校验报告
    if [[ "$GENERATE_REPORT" == true ]]; then
        generate_verification_report
    fi
    
    # 显示校验摘要
    display_verification_summary
    
    # 根据校验结果退出
    if [[ $FAILED_TESTS -gt 0 ]]; then
        exit $ERROR_GENERAL
    else
        exit $ERROR_SUCCESS
    fi
}

# 脚本入口点
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi